﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Krile.Common;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using Highkick.Common;
using Krile.Kernel;

namespace Highkick.API
{
    public class ParseXML
    {
        public Data.HStatus[] GetStatuses(Stream s)
        {
            var xd = XDocument.Load((XmlReader.Create(s)));
            var statusdocs = xd.Descendants("status");
            List<Data.HStatus> hs = new List<Highkick.Data.HStatus>();
            foreach (var st in statusdocs)
            {
                var news = new Data.HStatus();
                try
                {
                    news.Id = st.Element("id").Value;
                    news.CreatedAt = DateTime.Parse(st.Element("created_at").Value);
                    news.FavoredNum = int.Parse(st.Element("favorited").Value);
                    var repto = st.Element("in_reply_to_status_id").Value;
                    if (!String.IsNullOrEmpty(repto))
                    {
                        news.ReplyData = new Krile.Kernel.Data.ReplyData(repto, st.Element("in_reply_to_user_id").Value);
                        news.Text = st.Element("text").Value.CreateXString(st.Element("in_reply_to_user_id").Value);
                    }
                    else
                    {
                        news.Text = st.Element("text").Value.CreateXString(null);
                    }
                    news.Keyword = st.Element("keyword").Value;
                    news.StatusPage = new Uri(st.Element("link").Value);
                    news.User = new Data.HUser();
                    news.User.Id = st.Element("user").Element("id").Value;
                    news.User.Name = st.Element("user").Element("name").Value;
                    news.User.IconUri = new Uri(st.Element("user").Element("profile_image_url").Value);
                    news.User.ProfileUri = new Uri(st.Element("user").Element("url").Value);
                    news.Commands = new Krile.Kernel.Control.Surface.CommandButton[] { new Common.HatenaStar(news) };
                    hs.Add(news);
                }
                catch(Exception e)
                {
                    Bridge.DebugReporter.AddReport(e);
                }
            }
            return hs.ToArray();
        }

        public string[] GetKeywords(Stream s)
        {
            var xd = XDocument.Load((XmlReader.Create(s)));
            var statusdocs = xd.Descendants("related_keywords");
            List<string> kws = new List<string>();
            foreach (var st in statusdocs)
            {
                kws.Add(st.Value);
            }
            return kws.ToArray();
        }
    }
}
